import { getUuid } from "@/utils/utils";
import { Button, Drawer, Form, Icon, Input, InputNumber, message, Select, Tag } from "antd";
import { formatMessage } from 'umi-plugin-react/locale';
import React from "react";
import EditTag from "./editTag";
import { adminList } from "@/services/userProfile";
import UserSession from "@/UserSession";
import { configurationAdd, configurationDetail, configurationEdit } from "@/services/workOrder";
import { selfBuiltList } from "@/services/aigcUser";

class ConfigEdit extends React.Component{
  constructor(props){
    super(props);
    this.state = {
      visible:false,
      id:null,
      settingList:[
        {
          id:getUuid(),
        }
      ],
      userList:[]
    }
  }

  componentDidMount(){
    if(this.props.onRef){
      this.props.onRef(this)
    }
  }

  initData = id => {
    if(id){
      this.setState({
        id,
        visible:true
      },() => {
        this.getDetail(id)
      })
    }else{
      this.setState({
        visible:true
      })
    }

    if(!UserSession.getCurrentUser().isAdmin){
      //乙方-直接获取用户列表
      this.getUserList()
    }
  }

  getDetail = async id => {
    const res = await configurationDetail({id})
    this.props.form.setFieldsValue({
      ruleName:res.ruleName,
      remark:res.remark,
      conditionValue:res.conditionValue,
      userType:res.userIds && res.userIds.length > 0 ? 0 : 1,
      orderCode:res.orderCode
    })
    if(res.userIds && res.userIds.length > 0){
      this.getUserList()
      this.props.form.setFieldsValue({userIds:res.userIds})
    }
    this.setState({
      settingList:res.conditionRules
    },() => {
      for(const item of res.conditionRules){
        this.props.form.setFieldsValue({
          [`compareWay_${item.id}`]:item.compareWay,
          [`content_${item.id}`]:item.content,
          [`type_${item.id}`]:item.type
        })
      }
    })
  }

  onClose = () => {
    this.props.form.resetFields()
    this.setState({
      visible:false,
      id:null,
      settingList:[{id:getUuid(),}]
    })
  }

  addCondition = () => {
    let list = this.state.settingList
    list.push({
      id:getUuid()
    })
    this.setState({
      settingList:list
    })
  }

  validateForm = () => {
    const that = this;
    that.props.form.validateFields((error,values) => {
      if(!error){
        const { settingList } = that.state;
        let conditionRules = []
        for(const item of settingList){
          conditionRules.push({
            compareWay:values[`compareWay_${item.id}`],
            content:values[`content_${item.id}`],
            type:values[`type_${item.id}`],
          })
        }
        let obj = {
          ruleName:values.ruleName,
          remark:values.remark,
          conditionValue:values.conditionValue,
          conditionRules,
          userIds:values.userIds ? values.userIds : [],
          applicationId:UserSession.getCurrentUser().applicationId,
          orderCode:values.orderCode
        }
        that.doSubmit(obj)
        
      }
    })
  }

  doSubmit = async data => {
    const { id } = this.state;
    let res = {}

    if(id){
      data.id = id
      res = await configurationEdit(data)
    }else{
      res = await configurationAdd(data)
    }
     
    message.info(res.message)
    if(res.code == -1){}else{
      this.props.refreshList()
      this.onClose()
    }
  }

  doDelete = id => {
    let list = this.state.settingList.filter(item => item.id != id)
    this.setState({
      settingList:list
    })
  }

  changeUserType = value => {
    if(value == 0){
      this.getUserList()
    }
  }

  getUserList = async () => {
    let userList = []
    if(UserSession.getCurrentUser().isAdmin){
      //甲方管理员
      const res = await adminList({current:1,size:999999,applicationId:UserSession.getCurrentUser().applicationId})
      userList =res.records
    }else{
      //乙方
      const res = await selfBuiltList({current:1,size:999999,categoryId:"",name:""})
      userList =res.records
    }
    
    this.setState({userList})
  }

  render(){
    const { visible,id,settingList,userList } = this.state;
    const { form:{getFieldDecorator,getFieldValue} } = this.props;
    const formItemLayout = {
      labelCol: {
        xs: { span: 24 },
        sm: { span: 4 },
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 20 },
      },
    };
    return(
      <Drawer
        visible={visible}
        title={id ? formatMessage({id: 'pages.workOrder.policyConfiguration.configEdit.editRule'}) : formatMessage({id: 'pages.workOrder.policyConfiguration.configEdit.addRule'})}
        width={700}
        onClose={this.onClose}
      >
        <Form {...formItemLayout} style={{marginBottom:60}}>
          <Form.Item label={formatMessage({id: 'pages.workOrder.policyConfiguration.configEdit.ruleName'})}>
            {getFieldDecorator("ruleName",{rules:[{required:true,message:formatMessage({id: 'pages.workOrder.policyConfiguration.configEdit.validation.enterName'})}]})(
              <Input />
            )}
          </Form.Item>
          <Form.Item label={formatMessage({id: 'pages.workOrder.policyConfiguration.configEdit.remark'})}>
            {getFieldDecorator("remark")(
              <Input.TextArea autoSize={{minRows:3,maxRows:5}} />
            )}
          </Form.Item>
          <h3>{formatMessage({id: 'pages.workOrder.policyConfiguration.configEdit.ruleSetting'})}</h3>
          <div style={{border:'1px solid #cccccc',borderRadius:8,padding:10}}>
            <Form.Item label={formatMessage({id: 'pages.workOrder.policyConfiguration.configEdit.conditionSetting'})}>
              {getFieldDecorator("conditionValue",{rules:[{required:true,message:formatMessage({id: 'pages.workOrder.policyConfiguration.configEdit.validation.selectCondition'})}]})(
                <Select>
                  <Select.Option value={1}>{formatMessage({id: 'pages.workOrder.policyConfiguration.configEdit.all'})}</Select.Option>
                  <Select.Option value={0}>{formatMessage({id: 'pages.workOrder.policyConfiguration.configEdit.any'})}</Select.Option>
                </Select>
              )}
            </Form.Item>
            {
              settingList.map((item,index) => {
                return (
                  <div key={item.id} style={{padding:10,background:"#f9f9f9",borderRadius:8,position:'relative',marginBottom:10}}>
                    <Form.Item label={formatMessage({id: 'pages.workOrder.policyConfiguration.configEdit.matchMethod'})}>
                      {getFieldDecorator("compareWay_"+item.id,{rules:[{required:true,message:formatMessage({id: 'pages.workOrder.policyConfiguration.configEdit.validation.selectMatchMethod'})}]})(
                        <Select style={{width:200}}>
                          <Select.Option value={0}>{formatMessage({id: 'pages.workOrder.policyConfiguration.configEdit.equal'})}</Select.Option>
                          <Select.Option value={1}>{formatMessage({id: 'pages.workOrder.policyConfiguration.configEdit.notEqual'})}</Select.Option>
                        </Select>
                      )}
                    </Form.Item>
                    <Form.Item label={formatMessage({id: 'pages.workOrder.policyConfiguration.configEdit.matchType'})}>
                      {
                        getFieldDecorator("type_"+item.id,{initialValue:0})(
                          <Select>
                            <Select.Option value={0}>{formatMessage({id: 'pages.workOrder.policyConfiguration.configEdit.keyword'})}</Select.Option>
                            <Select.Option value={1}>{formatMessage({id: 'pages.workOrder.policyConfiguration.configEdit.regex'})}</Select.Option>
                          </Select>
                        )
                      }
                    </Form.Item>
                    <Form.Item label={formatMessage({id: 'pages.workOrder.policyConfiguration.configEdit.matchContent'})}>
                      {
                        getFieldDecorator("content_"+item.id)(
                          <Input placeholder={formatMessage({id: 'pages.workOrder.policyConfiguration.configEdit.multipleSeparatedBy'})} />
                        )
                      }
                    </Form.Item>
                    <Icon type="delete" style={{position:"absolute",right:10,top:10,cursor:"pointer"}} onClick={() => this.doDelete(item.id)} />
                  </div>
                )
              })
            }
            <Button type="link" icon="plus" onClick={this.addCondition}>
              {formatMessage({id: 'pages.workOrder.policyConfiguration.configEdit.addCondition'})}
            </Button>
          </div>

          <h3 style={{marginTop:20}}>{formatMessage({id: 'pages.workOrder.policyConfiguration.configEdit.thenPerformOperation'})}</h3>
          {
            UserSession.getCurrentUser().isAdmin ? (
                                  <Form.Item label={formatMessage({id: 'pages.workOrder.policyConfiguration.configEdit.assignee'})}>
                {getFieldDecorator("userType",{rules:[{required:true,message:formatMessage({id: 'pages.workOrder.policyConfiguration.configEdit.validation.selectProcessMethod'})}]})(
                  <Select onChange={this.changeUserType}>
                    <Select.Option value={0}>{formatMessage({id: 'pages.workOrder.policyConfiguration.configEdit.company'})}</Select.Option>
                    <Select.Option value={1}>{formatMessage({id: 'pages.workOrder.policyConfiguration.configEdit.serviceProvider'})}</Select.Option>
                  </Select>
                )}
              </Form.Item>
            ) : ''
          }
          {
            getFieldValue("userType") == 0 || !UserSession.getCurrentUser().isAdmin ? (
              <Form.Item label={UserSession.getCurrentUser().isAdmin ? ' ' : formatMessage({id: 'pages.workOrder.policyConfiguration.configEdit.assignHandler'})} colon={false}>
                {getFieldDecorator("userIds",{rules:[{required:true,message:formatMessage({id: 'pages.workOrder.policyConfiguration.configEdit.validation.selectAssigneeMethod'})}]})(
                  <Select mode="multiple" placeholder={formatMessage({id: 'pages.workOrder.policyConfiguration.configEdit.selectEngineer'})}>
                    {
                      userList.map(item => (
                        <Select.Option value={item.id}>{item.name || item.userName}</Select.Option>
                      ))
                    }
                  </Select>
                )}
              </Form.Item>
            ) : ''
          }
                              <Form.Item label={formatMessage({id: 'pages.workOrder.policyConfiguration.configEdit.priority'})}>
            {getFieldDecorator("orderCode",{rules:[{required:true,message:formatMessage({id: 'pages.workOrder.policyConfiguration.configEdit.validation.enterPriority'})}],initialValue:0})(
              <InputNumber min={0} precision={0} />
            )}
          </Form.Item>

        </Form>

        <div
          style={{
            position: 'absolute',
            right: 0,
            bottom: 0,
            width: '100%',
            borderTop: '1px solid #e9e9e9',
            padding: '10px 16px',
            background: '#fff',
            textAlign: 'right',
          }}
        >
          <Button onClick={this.onClose} style={{ marginRight: 8 }}>
            {formatMessage({id: 'pages.workOrder.policyConfiguration.configEdit.cancel'})}
          </Button>
          <Button onClick={this.validateForm} type="primary">
            {formatMessage({id: 'pages.workOrder.policyConfiguration.configEdit.confirm'})}
          </Button>
        </div>
      </Drawer>
    )
  }
}

export default Form.create()(ConfigEdit)